package com.it.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.it.bean.Dict;
import com.it.mapper.DictMapper;
import com.it.page.PageQuery;
import com.it.service.DictService;
import com.it.utils.AppUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("dictService")
@RequiredArgsConstructor
public class DictServiceImpl implements DictService {

    private final DictMapper dictMapper;

    @Override
    public List<Dict> single(String field) {
        Dict condition = new Dict();
        condition.setField(field);
        condition.setDeleted(false);
        return dictMapper.select(condition);
    }

    @Override
    public Map<String, List<Dict>> many(List<String> fields) {
        Map<String, List<Dict>> dataMap = new HashMap<>();
        for (String field : fields) {
            List<Dict> ds = single(field);
            dataMap.put(field, ds);
        }
        return dataMap;
    }

    @Override
    public PageInfo<Dict> page(PageQuery<Dict> pageQuery) {
        PageHelper.startPage(pageQuery.getPage(), pageQuery.getPageSize());
        Dict condition = pageQuery.getQueryBody();
        condition.setDeleted(false);
        List<Dict> ds = dictMapper.select(condition);
        return new PageInfo<>(ds);
    }

    @Override
    public void delete(Long id) {
        Dict dict = dictMapper.selectByPrimaryKey(id);
        dict.setDeleted(true);
        AppUtils.forUpdateAudit(dict);
        dictMapper.updateByPrimaryKeySelective(dict);
    }

    @Override
    public void save(Dict dict) {
        if (dict.getId() == null) {
            AppUtils.forSaveAudit(dict);
            dictMapper.save(dict);
        } else {
            AppUtils.forUpdateAudit(dict);
            dictMapper.updateByPrimaryKeySelective(dict);
        }
    }
}
